package com.zero.ava.service.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.slf4j.Logger;

import com.zero.ava.impl.kernel.ComponentRegistry;
import com.zero.ava.service.AbstractService;

public class NioMinaService extends AbstractService {

	private Logger logger;

	/**
	 * 服务启动端口
	 */
	private int port;

	/**
	 * 接收器
	 */
	private IoAcceptor acceptor;

	/**
	 * 消息处理
	 */
	private IoHandlerAdapter handler;

	/**
	 * 会话过滤器
	 */
	private IoFilter sessionfilter;
	/**
	 * 编解码器
	 */
	private IoFilter codec;

	protected NioMinaService(Properties properties, ComponentRegistry systemRegistry, Logger logger) {
		super(properties, systemRegistry, logger);
	}

	@Override
	public void init(Object configuration) {

		acceptor.getSessionConfig().setReadBufferSize(2048);
		// acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60000);
		// 消息处理
		acceptor.setHandler(handler);
		// 创建接收器控制器
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		// 会话拦截器
		chain.addLast("sessionfilter", sessionfilter);
		// 编解码器
		chain.addLast("Codec", codec);
		// 线程池
		chain.addLast("ReceivedThreadPool", new ExecutorFilter(Executors.newFixedThreadPool(400, new ThreadFactory() {
			private int num = 1;

			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				thread.setName("Mina thread poll -" + num++);
				return thread;
			}
		})));

		try {
			acceptor.bind(new InetSocketAddress(this.getPort()));
		} catch (IOException e) {
			e.printStackTrace();
		}

		logger.info("start port:" + getPort());
	}

	@Override
	protected void doReady() throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	protected void doShutdown() {
		// TODO Auto-generated method stub
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}
